﻿var app = angular.module('itsmApp', ['itsm-dep']);
var serverIp = "http://192.168.3.251";//"http://31.2.3.2";//http://192.168.1.41//31.2.3.2//
app.run(['$rootScope', '$state', '$stateParams','Restangular','$cookieStore',
function ($rootScope, $state, $stateParams, Restangular,$cookieStore) {

    // Attach Fastclick for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers
    FastClick.attach(document.body);

    // Set some reference to access them from any scope
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

    // GLOBAL APP SCOPE
    // set below basic information
    $rootScope.app = {
        name: '农商行', // name of your project
        author: '农商行运维管理平台', // author's name or company name
        description: '武汉农村商业银行运维管理平台', // brief description
        version: '1.0', // current version
        year: ((new Date()).getFullYear()), // automatic current year (for copyright information)
        isMobile: (function () {// true if the browser is a mobile device
            var check = false;
            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                check = true;
            };
            return check;
        })(),
        isLoginFixed: false,
        layout: {
            // isLoginFixed: true,
            isNavbarFixed: true, //true if you want to initialize the template with fixed header
            isSidebarFixed: true, // true if you want to initialize the template with fixed sidebar
            isSidebarClosed: false, // true if you want to initialize the template with closed sidebar
            isFooterFixed: true, // true if you want to initialize the template with fixed footer
            theme: 'theme-5', // indicate the theme chosen for your project
            logo: 'assets/images/logo.png' // relative path of the project logo
        }
    };
    Restangular.setFullRequestInterceptor(function (element, operation, what, url, headers, queryParams) {
      var token = $cookieStore.get('Auth-Token')||null;
      var isReportUri = url.indexOf('saiku')>0; 
      if(token&&isReportUri){
        return {
          element: element,
          params: queryParams,
          headers: _.extend({}, headers, {'X-Auth-Token': $cookieStore.get('Auth-Token') || null})  
        };
      }else{
        return {
          element: element,
          params: queryParams,
          headers: headers
        };
      }
    });
    
    // $rootScope.nickname ='lijin';

    // $rootScope.user = {
    //     name: 'Peter',
    //     job: 'ng-Dev',
    //     picture: 'app/img/user/02.jpg'
    // };
}]);
// translate config
app.config(['$translateProvider',
function ($translateProvider) {

    // prefix and suffix information  is required to specify a pattern
    // You can simply use the static-files loader with this pattern:
    $translateProvider.useStaticFilesLoader({
        prefix: 'assets/i18n/',
        suffix: '.json'
    });

    // Since you've now registered more then one translation table, angular-translate has to know which one to use.
    // This is where preferredLanguage(langKey) comes in.
    $translateProvider.preferredLanguage('zh');

    // Store the language in the local storage
    $translateProvider.useLocalStorage();

}]);
// Angular-Loading-Bar
// configuration
app.config(['cfpLoadingBarProvider',
function (cfpLoadingBarProvider) {
    cfpLoadingBarProvider.includeBar = true;
    cfpLoadingBarProvider.includeSpinner = false;
}]);



/**
 * 
 */
app.config(['RestangularProvider', function(RestangularProvider){
   RestangularProvider.setBaseUrl('/dev/');
}]);

app.factory('UserRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(serverIp+':9002/services/');
  });
});

app.factory('api_user', ['UserRestangular', function(UserRestangular){
    var basePath = "user/";
    return {

    };
}]);

app.factory('api_login', ['UserRestangular', function(UserRestangular){
  var loginService = UserRestangular.all("auth");
  return {
    login: function(username, password){
      return loginService.customPOST({'username':username,'password':password}, 'login',{});
    },
    // logout: function(sessionid,userid){
    //   return loginService.customPOST(sessionid + '/' + userid);
    // },
    sso: function(nickname){
      return loginService.customGET('sso/' + nickname);
    },
    resetpwd: function(userid){
      return loginService.customGET('resetpwd/' + userid);
    },
    uppwd: function(data){
      return loginService.customPOST(data, 'uppwd',{});
    }
  }
}])


app.factory('api_user_data', ['UserRestangular', function(UserRestangular){
    var dataService = UserRestangular.all("data");
    return {
        validate:function(data){
          return dataService.customPOST(data,'validate/role', {});
        },
        fetchDataList: function(model, data){
          return dataService.customPOST(data,'fetchDataList/' + model, {});
        },
        fetchData : function(model, data){
          return dataService.customPOST(data, 'fetchData/' + model, {});
        },
        addData: function(model, data){
          return dataService.customPOST(data, 'addData/' + model, {});
        },
        rmvData: function(model, data){
          return dataService.customPOST(data, 'rmvData/' + model, {});
        }
    };
}]);
// app.factory('DpmRestangular', function(Restangular) {
//   return Restangular.withConfig(function(RestangularConfigurer) {
//     RestangularConfigurer.setBaseUrl(serverIp+':9008/data/');
//   });
// });

// app.factory('api_bpm_dbca', ['DpmRestangular', function(DpmRestangular){
//     var bpm = DpmRestangular.all("bpm");
    // return {
    //     impFileData: function(pdKey){
    //       return bpm.customPOST( 'impFileData/' + pdKey);
    //     },
    // };
// }]);
app.factory('BpmRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    // RestangularConfigurer.setBaseUrl("http://168.166.3.41"+':9008/api/');
    RestangularConfigurer.setBaseUrl(serverIp+':9008/api/');
  });
});

app.factory('api_statistic', ['BpmRestangular', function(BpmRestangular){
	var statistic = BpmRestangular.all("statistic");
    return {
    	query: function(data, rptId){
    	 	return statistic.customPOST(data, 'unidimensional/'+rptId, {});
    	}
   	};
}]);

app.factory('api_bpm', ['BpmRestangular', function(BpmRestangular){
    var process = BpmRestangular.all("process");
    return {
        deploy: function(data){
          return process.customPOST(data, 're/model/deploy', {});
        },
        list: function(){
          return process.customGET('re/model/list');
        },
        modelsource: function(pdId){
          return process.customGET('re/model/' + pdId + '/source');
        },
        savemodel: function(pdId,data){
          return process.customPOST(data, 're/model/' + pdId + '/save' , {});
        },
        removemodel: function(modelId){
          return process.customGET('re/model/' + modelId + '/remove');
        }
    };
}]);

app.factory('api_bpm_domain', ['BpmRestangular', function(BpmRestangular){
    var bpmService = BpmRestangular.all("bpm");
    return {
        fetchtask: function(pdKey,data){
          return bpmService.customPOST(data, 'fetchTask/' + pdKey, {});
        },
        start : function(pdKey,data){
          return bpmService.customPOST(data, 'start/' + pdKey, {});
        },
//        complete: function(pdKey, userId, data){
//          return bpmService.customPOST(data, 'completeTask/' + pdKey + '/' + userId, {});
//        },
        complete: function(taskId, userId, data){
            return bpmService.customPOST(data, 'completeTask/' + taskId + '/' + userId, {});
        },
        completeUpgrade: function(data){
          return bpmService.customPOST(data, 'upgradeIncident', {});
        },
        save: function(taskId,data){
          return bpmService.customPOST(data, 'saveTaskVar/' + taskId, {});
        },
        claimtask: function(taskId, data){
          return bpmService.customPOST(data, 'claimTask/' + taskId, {});
        },
        history: function(processId){
          return bpmService.customGET('history/' + processId);
        },
        upgrade: function(processInstanceId,taskId,data){
          return bpmService.customPOST(data, 'upgradeIncident/' + processInstanceId + '/' + taskId , {});
        },
        listAttachments: function(processId, data){
          return bpmService.customPOST(data, 'getAttachmentList/' + processId , {});
        },
        saveAttachments: function(processId,taskId,userId, data){
          return bpmService.one('saveAttachments/'+processId+'/'+taskId+'/'+userId);
        },
        downloadAttachment: function(attachmentId){
          return bpmService.one('getAttachmentContent/' + attachmentId);
        },
        startformkey: function(pdKey){
          return bpmService.customGET('startformkey/' + pdKey);
        },  
        taskformkey: function(taskId){
          return bpmService.customGET('taskformkey/' + taskId);
        },
        workernumber: function(type){
          return bpmService.customGET('restful/' + type);
        }
    };
}]);

app.factory('api_bpm_data', ['BpmRestangular', function(BpmRestangular){
    var dataService = BpmRestangular.all("data");
    return {
        impFileData: function(){
          return dataService.one('/impFileData/bpm_scheduleorder');
        },
        fetchDataList: function(model, data){
          return dataService.customPOST(data,'fetchDataList/'+model, {});
        },
        fetchData : function(model, dataId){
          return dataService.customGET('fetchData/' + model + '/' + dataId);
        },
        addData: function(model, data){
          return dataService.customPOST(data, 'addData/' + model, {});
        },
        rmvData: function(model, data){
          return dataService.customPOST(data, 'rmvData/' + model, {});
        }
    };
}]);

app.factory('api_bpm_schedule', ['BpmRestangular', function(BpmRestangular){
    var dataService = BpmRestangular.all("data");
    return {
        getScheduleClass: function(){
          var data={
            "idx":"0",
            "sum":"1000"
          };
          return dataService.customPOST(data,'fetchDataList/scheduleclass', {});
        },
        fetchList: function(startTime, endTime,userId, queryKey){
          var scheduleOrder = {
            "scheduleorder":{
              "startTime" : startTime,
              "endTime" : endTime
            },
            "idx":"0",
            "sum":"1000"
          };
          if(userId){
            scheduleOrder['scheduleorder']['user'] = userId;
          }
          if(queryKey){
            scheduleOrder['scheduleorder']['description'] = queryKey;
          }
          return dataService.customPOST(scheduleOrder,'fetchDataList/scheduleorder', {});
        },
        fetchData : function(dataId){
          return dataService.customGET('fetchData/scheduleorder/' + dataId);
        },
        update : function(data){
          return dataService.customPOST(data,'updData/scheduleorder',{});
        },
        add: function(data){
          return dataService.customPOST(data, 'addData/scheduleorder', {});
        },
        remove: function(data){
          return dataService.customPOST(data, 'rmvData/scheduleorder', {});
        },
        fetchSchedule: function(userId, startTime, endTime){
          var scheduleData = {
            "schedulewatch":{
              "type":"1",
              "user":{
                "id": userId
              },
              "startTime":startTime,
              "endTime":endTime
            },
            "idx":"0",
            "sum":"100"
          };
          return dataService.customPOST(scheduleData, 'fetchDataList/schedulewatch', {});
        },
        queryRecieveSwitch: function(userId){
          var handleSwitch = {
            "schedulewatch":{
              "type":"3",
              "user":{
                "id":userId
              }
            },
            "idx":"0",
            "sum":"10"
          };
          return dataService.customPOST(handleSwitch, 'fetchDataList/schedulewatch', {});
        },
        queryHandleoutSwitch: function(userId){
          var handleSwitch = {
            "schedulewatch":{
              "type":"2",
              "user":{
                "id":userId
              }
            },
            "idx":"0",
            "sum":"10"
          };
          return dataService.customPOST(handleSwitch, 'fetchDataList/schedulewatch', {});
        },
        handleSchedule: function(data){
          return dataService.customPOST(data, 'updData/schedulewatch', {});
        },
        querySwitch: function(filterData){
          var switchData = {
            "scheduleorder":{
                "type":"4"
            },
            "idx":filterData.idx,
            "sum":filterData.sum
          };
          return dataService.customPOST(switchData, 'fetchDataList/scheduleorder', {}); 
        },
        query: function(filterData){
          var switchData = {
            "scheduleorder":filterData.scheduleorder,
            "idx":filterData.idx,
            "sum":filterData.sum
          };
          return dataService.customPOST(switchData, 'fetchDataList/scheduleorder', {}); 
        }
    };
}]);


app.factory('ConfigureRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(serverIp+':9007/config/');
  });
});

app.factory('api_configure_form',['ConfigureRestangular', function(ConfigureRestangular){
    var formService = ConfigureRestangular.all("form");
    
    return {
        renderForm: function(formKey,userId, processInstanceId){
          if(processInstanceId){
              return formService.customGET('renderForm/' + formKey + "/" + processInstanceId + "/" + userId);
          }else{
              return formService.customGET('renderForm/' + formKey + "/000000/" + userId);
          }
        },
        renderList : function(formKey){
          return formService.customGET('renderList/' + formKey);
        },
        renderTabForm: function(classify){
          return formService.customGET('renderTabForm/' + classify);
        }
    };
}]);


app.factory('api_configure_data',['ConfigureRestangular', function(ConfigureRestangular){
    var dataService = ConfigureRestangular.all("data");
    return {
        fetchDataList: function(model,data){
          return dataService.customPOST(data, 'fetchDataList/' + model , {});
        },
        fetchData : function(model,data){
          return dataService.customPOST(data, 'fetchData/' + model, {});
        },
        addData: function(model,data){
          return dataService.customPOST(data, 'addData/' + model, {});
        }
    };
}]);

app.factory('SolutionRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    //RestangularConfigurer.setBaseUrl('http://168.166.203.41:9000/services');
    RestangularConfigurer.setBaseUrl(serverIp+':9000/services');
  });
});

app.factory('api_solution', ['SolutionRestangular', function(SolutionRestangular){
    var solutionService = SolutionRestangular.all("solution");
    var data = SolutionRestangular.all("solutionData");
    var history = SolutionRestangular.all("solutionHistory");
    var review = SolutionRestangular.all("solution_review");
    var typeservice = SolutionRestangular.all("solutionType");
    var groupservice = SolutionRestangular.all("solutionGroup");

    return {
        findSolutionByKeys: function(data){
          var key=data.key, status=data.status||0, pageIndex=data.pageIndex||0, pageSum=data.pageSum, treeIds=data.treeIds, userId=data.userId;
          if(angular.isUndefined(treeIds)){
              return solutionService.customGET('findSolutionByKeys/' + key + '/' +  status + '/' + pageIndex + '/' + pageSum + '/' + userId);
          }else{
              return solutionService.customGET('findSolutionByKeys/' + key + '/' +  status + '/' + pageIndex + '/' + pageSum + '/' + treeIds + '/' + userId);
          }
        },
        addSolution : function(){
          return solutionService.one('add');
        },
        update: function(){
          return solutionService.one('update');
        },
        addNotFile : function(data){
          return solutionService.customPOST(data, 'addNotFile/', {});
        },
        updateNotFile : function(data){
          return solutionService.customPOST(data, 'updateNotFile/', {});
        },
        searchSolutionByKey: function(key){
          return solutionService.customGET('searchSolutionByKey/' + key);
        },
        findSolutionById: function(id){
          return solutionService.customGET('check/' + id);  
        },
        findSolutions: function(id){
          return solutionService.customGET('check2/' + id);  
        },
        findSolutionDataByDateById: function(ndate,sid){
          return data.customGET('findSolutionDataByDateById/' + ndate + '/' + sid);
        },
        findSolutionTypeActions: function(userId){
          return typeservice.customGET('findSolutionTypeActions/' + userId);
        },
        findSolutionTypesUser: function(data){
          return typeservice.customPOST(data,'findSolutionTypesUser/' ,{});
        },
        addTypeUserAll: function(data){
          return typeservice.customPOST(data,'addTypeUserAll/' ,{});
        },
        hotRanking: function(num){
          return solutionService.customGET('hotRanking/' + num );
        },
        scoreRanking: function(num){
          return solutionService.customGET('scoreRanking/' + num );
        },
        fetchBBSSolutions: function(pageIndex, pageSum, sequence, userId){
          return solutionService.customGET('BBSSolutions/' + pageIndex + '/' + pageSum +'/'+  sequence + '/' + userId);
        },
        queryBBSSolutions: function(pageIndex, pageSum, sequence, userId, key){
          return solutionService.customGET('BBSSolutions/' + pageIndex + '/' + pageSum +'/'+  sequence + '/' + userId + '/' + key);
        },
        updateSolutionStatus: function(data){
          return solutionService.customPOST(data, 'updateSolutionStatus',{});
        },
        getSolutionNumber: function(){
          return solutionService.customGET('getSolutionNumber');
        },
        addSolutionType: function(data){
          return typeservice.customPOST(data ,'add', {});
        },
        updateSolutionType: function(data){
          return typeservice.customPOST(data ,'update', {});
        },
        removeSolutionType: function(id){
          return typeservice.customGET('delete/'+id);
        },
        getSolutionType: function(id){
          return typeservice.customGET('' + id);
        },
        getTree: function(typeId, groupId, flag){
          return typeservice.customGET('getTree/'+typeId+'/'+groupId+'/' + flag);
        },
        checkCommentScoreByUserIds:function(userId, id){
          return review.customGET('findCommentScore/'+userId + '/' + id);
        },
        addSolutionReview:function(data){
          return review.customPOST(data,'addSolutionReview',{});
        },
        findSolutionReviewById:function(id){
          return review.customGET('findSolutionReviewByType/' + id);
        },
        saveAllUserAuth:function(solutionId, flag){
          return solutionService.customGET('saveAllUserTrees/' + solutionId + '/' + flag);
        },
        updatermvSolutionType: function(typeId, groupId, userIds, flag){
          return typeservice.customGET('delOrUpdateTrees/' + typeId + '/' + groupId + '/'+userIds+ '/'+flag);
        },
         findSolutionGroup:function(id){
          return groupservice.customGET('findSolutionGroup/'+id);
        },
         saveSolutionGroup: function(id,data){
          return groupservice.customPOST(data,'saveSolutionGroup/'+id);
        },
        getSolutionDowpath: function(){
            return solutionService.one('download');
        }

    };
}]);

app.factory('CMDBRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(serverIp+':9005/api/cmdb/');
  });
});

app.factory('api_cmdb',['CMDBRestangular', function(CMDBRestangular){
  var ciService = CMDBRestangular.all("ci");
  var edgeService = CMDBRestangular.all("edge");
  var traversal = CMDBRestangular.all("traversal");
  var downloadService = CMDBRestangular.all("download");
  var exportService = CMDBRestangular.all("export");
  var importService = CMDBRestangular.all("import");
  function serializeData( data ) { 
      // If this is not an object, defer to native stringification.
      if ( ! angular.isObject( data ) ) { 
          return( ( data == null ) ? "" : data.toString() ); 
      }

      var buffer = [];

      // Serialize each key in the object.
      for ( var name in data ) { 
          if ( ! data.hasOwnProperty( name ) ) { 
              continue; 
          }

          var value = data[ name ];

          buffer.push(
              encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value )
          ); 
      }

      // Serialize the buffer and clean it up for transportation.
      var source = buffer.join( "&" ).replace( /%20/g, "+" ); 
      return( source ); 
  }

  return {
        create: function(data){
          return ciService.customPOST(data,'', {});
        },
        put: function(data, id){
          return ciService.customPUT(data, id, {});
        },
        remove: function(id){
          return ciService.customDELETE(id);
        },
        removeByUUId: function(uuid){
          return ciService.customDELETE('uuid/' + id, {},{'Content-Type': 'application/json'});
        },
        removeRefById: function(id){
          return ciService.customDELETE(id + '/ref');
        },
        find: function(id){
          return ciService.customGET(id);
        },
        find: function(id){
          return ciService.customGET(id);
        },
        findByUUId: function(uuid){
          return ciService.customGET('?uuid=' + uuid);
        },
        query: function(data){
          return ciService.customGET('query', data);
        },
        findRefById: function(id){
          return ciService.customGET(id + '/refs');
        },
        types: function(){
          return CMDBRestangular.customGET('types');
        },
        createRef: function(data){
          return edgeService.customPOST(data,'', {});
        },
        putRef: function(data, id){
          return edgeService.customPUT(data,'' + id, {});
        },
        removeRef: function(id){
          return edgeService.customDELETE(id,{},{'Content-Type': 'application/json'});
        },
        traversal: function(uuid){
          return traversal.customGET(uuid);
        },
        traversalRel: function(uuid, relation){
          return traversal.customGET(uuid + '/' + relation + '/' + 'none');
        },
        export: function(label){
          return exportService.customGET('nodes/' + label);
        },
        import: function(){
          return importService.one('/nodes');
        },
        download: function(label){
          return downloadService.one('/label');
        }
    };
}]);
app.factory('MonitorRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(serverIp+':9004/services');
  });
});

app.factory('api_monitor', ['MonitorRestangular', function(MonitorRestangular){
    //http://127.0.0.1:9004/services/ftpFile/monitor/bankTip/
    var process = MonitorRestangular.all("ftpFile/monitor");
    return {
        bankTip: function(id){
          return process.customGET('bankTip/'+id);
        },
        list: function(){
          return process.customGET( 'list/1000' );
        },
        devList: function(id){
          return process.customGET('devList/'+id);
        },
        cpuList: function(){
          return process.customGET('cpuList/10');
        },
        memList: function(){
          return process.customGET('memList/10');
        },
        storageList: function(){
          return process.customGET('storageList/10');
        },
        transData: function(){
          return process.customGET('transData/5');
        },
        banklist: function(){
          return process.customGET('banklist');
        },
        app: function(id){
          return process.customGET('app/'+id);
        },
        beita: function(id){
          return process.customGET('beita/'+id);
        },
        gongji: function(id){
          return process.customGET('gongji/'+id);
        }

    };
}]);

app.factory('ReportRestangular', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    //RestangularConfigurer.setBaseUrl('http://127.0.0.1:9005/api/cmdb/');
    RestangularConfigurer.setBaseUrl(serverIp+'/saiku/rest');
    //saiku/rest/saiku/api/query/execute/
  });
});

app.factory('api_report', ['ReportRestangular','Restangular', function(MonitorRestangular, Restangular){
  var reportService = MonitorRestangular.all("saiku/api");
  var authService = MonitorRestangular.one("saiku/session");
    return {
      getLicenseKey: function(){
         return Restangular.one('assets/').customGET('api/reportToken.js');
      },
      // auth: function(){
      //   return authService.customPOST('username=admin&password=admin&language=zh'
      //   ,'', {}, {'Content-Type': 'application/x-www-form-urlencoded'});
      // },
      // session: function(){
      //   return authService.customGET('');
      // },
      list: function(){
        return reportService.customGET('repository?type=saiku');
        /**
        /saiku/api/repository
        path: /homes/home:admin/itsm_reports
        */
      },
      getMdx: function(path, uuid){
        var rdata = 'file='+path+'&formatter=flattened&language=zh';
        return reportService.customPOST(rdata,'query/'+uuid, {}, {'Content-Type': 'application/x-www-form-urlencoded'});
      },
      execute: function(data){
          return reportService.customPOST(data, 'query/execute', {}, {'Accept': 'application/json, text/javascript, */*'});
      },
      exportData: function(reportView, uuid, reportfileName){
          return  reportService.one('query/rest/export/xls/?exportname='+reportfileName+'xls');
      }   
    };
}]);

